#!/usr/bin/env python
import os
import sys
import json
import urlparse
from urlparse import parse_qs
import mysql.connector
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('/etc/fileserver/config.ini')

MYSQL_CONFIG = {
    'host': config.get("mysql", "host"),
    'user': config.get("mysql", "user"),
    'password': config.get("mysql", "password"),
    'database': config.get("mysql", "database"),
    'port': config.get("mysql", "port")
}

def save_file_to_database(file_uuid, file_name, downstatus):
    cnx = mysql.connector.connect(**MYSQL_CONFIG)
    cursor = cnx.cursor()

    query = ("INSERT INTO file_download (file_uuid, file_name, status) "
             "VALUES (%s, %s, %s) "
             "ON DUPLICATE KEY UPDATE status = %s")
    data = (file_uuid, file_name, downstatus, downstatus)

    cursor.execute(query, data)
    cnx.commit()

    cursor.close()
    cnx.close()

query_string = os.environ.get('QUERY_STRING', '')
params = parse_qs(query_string)
file_name = params.get('file_name', [None])[0]
file_uuid = params.get('file_uuid', [None])[0]
downstatus = params.get('downstatus', [None])[0]

if file_name and file_uuid and downstatus:
    try:
        downstatus = int(downstatus)
        save_file_to_database(file_uuid, file_name, downstatus)
        response = {'status': 'success'}
    except ValueError:
        response = {'status': 'error', 'message': 'Invalid downstatus value'}
else:
    response = {'status': 'error', 'message': 'Missing parameters'}

print("Content-Type: application/json\n\n")
print(json.dumps(response))

